<template>
  <el-dialog
    :title="dialogObj.title"
    append-to-body
    :visible.sync="dialogObj.show"
    :close-on-click-modal="false"
    width="1000px"
  >
    <el-form
      status-icon
      ref="form"
      :model="form"
      label-width="150px"
      :rules="rules"
      :disabled="dialogObj.id == 1"
      v-if="dialogObj.show"
    >
      <el-form-item label="活动：" prop="activityId">
        <el-select
          v-model="form.activityId"
          placeholder="请选择活动"
          value-key="index"
          size="mini"
          @change="selectActivityOption"
        >
          <el-option
            v-for="(data, index) in activityList"
            :key="index"
            :label="data.activityName"
            :value="data.activityId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="场次：" required v-if="form.activityId">
        <el-checkbox-group
          v-if="dialogObj.id == ''"
          v-model="activitySession"
          size="mini"
          @change="changeCheck"
        >
          <span v-for="(item, index) in activitySessionList" :key="index">
            <el-checkbox :label="item.start" border>{{
              item.start
            }}</el-checkbox>
          </span>
        </el-checkbox-group>
        <div v-if="dialogObj.id == 1 && form.activityTime">
          <span
            class="text-raduis"
            v-for="(item, index) in form.activityTime.split(',')"
            :key="index"
          >
            {{ item }}
          </span>
          <!-- {{
          validateReplaceFun(form.activityTime)
        }} -->
        </div>
      </el-form-item>
      <el-form-item label="楼层配置：" required>
        <el-table :data="tableData" style="width: 100%" border size="mini">
          <el-table-column
            prop="floorId"
            label="楼层"
            align="center"
            width="100"
          >
            <template slot-scope="scope">
              <div>
                {{ scope.row.floorId | floorFilter }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="diningPosition"
            label="取货位置"
            align="center"
            width="240"
          >
            <template slot-scope="scope">
              <div>
                <el-input
                  v-if="dialogObj.id == ''"
                  type="textarea"
                  v-model="scope.row.diningPosition"
                  size="mini"
                  maxlength="100"
                  show-word-limit
                  resize="none"
                  :autosize="{ minRows: 2 }"
                  :placeholder="placeholderTips.diningPosition"
                ></el-input>
                <span v-if="dialogObj.id == 1">{{
                  scope.row.diningPosition
                }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="diningTime" label="取货时间" align="center">
            <template slot-scope="scope">
              <div>
                <el-time-picker
                  v-if="dialogObj.id == ''"
                  class="input-class"
                  is-range
                  v-model="scope.row.diningTime"
                  size="mini"
                  range-separator="~"
                  format="HH:mm"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                >
                </el-time-picker>
                <span v-if="dialogObj.id == 1">{{ scope.row.diningTime }}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <span style="color:red"
          >注：默认必须设置至少一个楼层，每个楼层的信息请成对设定，即：时间和位置同时设定,否则无效</span
        >
      </el-form-item>

      <el-form-item label="自动发送短信时间：" prop="sendTime">
        <span> 活动前 </span>
        <el-input
          v-model="form.sendTime"
          style="width:100px;"
          size="mini"
          :placeholder="placeholderTips.number"
        ></el-input>
        <span> 小时</span>
        <strong style="color:red;font-size:12px;">(默认不设置立即推送)</strong>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer" v-if="dialogObj.id == ''">
      <el-button type="primary" @click="sub" size="mini">确 定</el-button>
      <el-button @click="dialogObj.show = false" size="mini">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
import Cookie from "@u/cookie";
import { _debounce } from "@u/debounce";
import { FLOOROBJ } from "@u/wordbook";
import {
  placeholderTips,
  validateNumEmpty,
  validateTemplateActivity,
  validateReplace
} from "@u/validate";
import {
  getLocalActivityApi,
  addsmsconfigListapi,
  getsmsconfigDetailApi
} from "@s/api";
import timeFormat from "@u/timeFormat";
export default {
  name: "dialogCom",
  props: ["dialogObj"],
  data() {
    return {
      placeholderTips: placeholderTips,
      tags: [
        {
          diningTime: "",
          diningPosition: "",
          floorId: "1"
        },
        {
          diningTime: "",
          diningPosition: "",
          floorId: "2"
        },
        {
          diningTime: "",
          diningPosition: "",
          floorId: "3"
        },
        {
          diningTime: "",
          diningPosition: "",
          floorId: "4"
        },
        {
          diningTime: "",
          diningPosition: "",
          floorId: "5"
        },
        {
          diningTime: "",
          diningPosition: "",
          floorId: "6"
        }
      ],
      tableData: [],
      innerVisible: false,
      innerForm: {
        diningPosition: "",
        diningTime: "",
        floorId: "",
        isAdd: true
      },
      activityList: [],
      activitySessionList: {},
      activitySession: [],
      form: {
        activityId: "",
        activityName: "",
        activityTime: "",
        sendTime: "",
        smsType: 2 // 2 特许
      },
      rules: {
        sendTime: [
          { required: true, validator: validateNumEmpty, trigger: "change" }
        ],
        activityId: [
          { required: true, message: "请选择活动", trigger: "change" },
          { validator: validateTemplateActivity }
        ]
      }
    };
  },
  //过滤器
  filters: {
    floorFilter(val) {
      return FLOOROBJ[val];
    }
  },
  methods: {
    initDialog() {
      if (this.dialogObj.id) {
        this.form.activityId = this.dialogObj.form.activityId;
        this.form.activityName = this.dialogObj.form.activityName;
        this.form.activityTime = this.dialogObj.form.activityTime;
        this.form.sendTime = this.dialogObj.form.sendTime;
        this.tableData = JSON.parse(JSON.stringify(this.tags));
        this.getsmsconfigDetail(this.dialogObj.form.smsConfigId);
      } else {
        this.form.activityId = "";
        this.form.activityName = "";
        this.form.activityTime = "";
        this.form.sendTime = "";
        this.tableData = JSON.parse(JSON.stringify(this.tags));
      }
    },
    // 场次选择
    changeCheck(val) {
      this.form.activityTime = val.join(","); // 数组转字符串
    },
    // 获取查看短信详情
    getsmsconfigDetail(smsConfigId) {
      let json = {
        smsConfigId: smsConfigId
      };
      getsmsconfigDetailApi(json).then(res => {
        let list = res;
        list.forEach(item => {
          if (item.floorId) {
            this.tableData[item.floorId - 1].diningPosition =
              item.diningPosition;
            this.tableData[item.floorId - 1].diningTime = item.diningTime;
          }
        });
      });
    },
    selectActivityOption(val) {
      this.activitySession = [];
      let arr = this.activityList;
      arr.forEach(item => {
        if (item.activityId == val) {
          this.form.activityName = item.activityName;
          this.activitySessionList = JSON.parse(item.activityDates);
        }
      });
    },
    // 获取活动信息
    getActivityList() {
      getLocalActivityApi().then(res => {
        // 特许商品判断权限筛选
        // 查询是否有活动权限
        res = res.list;
        let getActivityId =
          JSON.parse(localStorage.getItem("mb_userInfo")).activityIds || "";
        if (getActivityId && getActivityId != "0") {
          // 单个活动用户
          getActivityId = getActivityId.split(","); // 字符串转数组
          // 活动权限筛选
          let activityArr = [];
          res.forEach(item => {
            if (getActivityId.indexOf(item.activityId) > -1) {
              activityArr.push(item);
            }
          });
          this.activityList = activityArr;
        } else {
          // 所有活动用户
          this.activityList = res;
        }

        // 判断回显的数据是否存在列表中
        if (this.dialogObj.id) {
          let findId = this.activityList.filter(item => {
            return item.activityId == this.form.activityId;
          });
          if (findId.length == 0) {
            let newArr = {
              activityName: this.form.activityName,
              activityId: this.form.activityId
            };
            this.activityList.push(newArr);
          }
        }
      });
    },
    sub: _debounce(function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.activityTime) {
            var json = JSON.parse(JSON.stringify(this.form));
            var flag = false;
            this.tableData.forEach(item => {
              if (item.diningPosition && item.diningTime) {
                flag = true;
              }
            });
            if (flag) {
              let formArr = [];
              this.tableData.forEach(item => {
                if (item.diningPosition && item.diningTime) {
                  var obj = {
                    diningTime:
                      timeFormat.minuteTime(item.diningTime[0]) +
                      "-" +
                      timeFormat.minuteTime(item.diningTime[1]),
                    diningPosition: item.diningPosition,
                    floorId: item.floorId,
                    activityId: json.activityId,
                    activityName: json.activityName,
                    activityTime: json.activityTime,
                    sendTime: json.sendTime,
                    smsType: json.smsType
                  };
                  formArr.push(obj);
                }
              });
              this.addSub(formArr);
            } else {
              this.$message({
                type: "warning",
                message: "至少配置一个楼层信息！"
              });
            }
          } else {
            this.$message({
              type: "warning",
              message: "至少配置一个场次！"
            });
          }
        }
      });
    }),
    addSub(json) {
      addsmsconfigListapi(json).then(() => {
        this.dialogObj.show = false;
        this.$emit("reflash");
        this.$message({
          type: "success",
          message: "操作成功！"
        });
      });
    },
    validateReplaceFun(val) {
      return validateReplace(val);
    }
  },
  watch: {
    "dialogObj.show"(val) {
      if (val) {
        this.initDialog();
        this.getActivityList();
      }
    }
  }
};
</script>
<style scoped lang="scss">
span {
  margin: 0 10px;
}
.floor-list {
  li {
    border: 1px solid #ddd;
    border-radius: 10px;
    padding: 0 8px;
    display: inline-block;
    margin: 10px;
  }
  span {
    cursor: pointer;
    margin: 0 5px;
  }
}
</style>
